//
//  SZLPersonInfoViewController.m
//  Shengzhuli
//
//  Created by 卡忙科技 on 16/8/1.
//  Copyright © 2016年 kamangkeji. All rights reserved.
//

#import "SZLPersonInfoViewController.h"
#import "PersonInfoViewCell.h"
#import "UIActionSheet+Extension.h"
#import "NickNamecell.h"
#import "PersonNetWork.h"
#import "SZLAccountHelper.h"
#import "MBProgressHUD+MJ.h"
#import "BirthDayTableViewCell.h"
#import "TimePickerView.h"
#import "NSDate+Extension.h"

#define AvatorPath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:@"avator.png"]

@interface SZLPersonInfoViewController ()<UITableViewDataSource,UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate>

@property (nonatomic,strong) UITableView *sourceTab;
@property (nonatomic,strong) NSArray *titles;
@property (nonatomic,strong) UIImage *avatorImage;//记录上传的图片
@property (nonatomic,assign) BOOL isSelect;//是否修改密码

@end

@implementation SZLPersonInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"个人信息";
    [self setView];
}
- (void)setView
{
    UIButton *saveBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 50, 30)];
    [saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    [saveBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    saveBtn.titleLabel.font = Font(16);
    [saveBtn addTarget:self action:@selector(saveClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:saveBtn];
    [self.view addSubview:self.sourceTab];
}
- (void)saveClick
{
    [self.view endEditing:YES];
    if (self.info.nickName.length<1) {
        [MBProgressHUD showError:@"请填写昵称" toView:self.view];
        return;
    }else if (self.info.birthday.length<1){
        [MBProgressHUD showError:@"请选择出生日期" toView:self.view];
        return;
    }
    [self saveInfo];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0.01;
    }
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, 10)];
    view.backgroundColor = RGBColorOne(240);
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 70;
    }
    return 44;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        PersonInfoViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([PersonInfoViewCell class])];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.info = self.info;
        if (self.avatorImage) {
            cell.avator = self.avatorImage;
        }
        return cell;
    }else if (indexPath.section == 1){
        NickNamecell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([NickNamecell class])];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.info = self.info;
        return cell;
    }
    BirthDayTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([BirthDayTableViewCell class])];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.info = self.info;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        [self takeAvator];
    }else if (indexPath.section == 2) {
        __WEAK
        [self.view endEditing:YES];//键盘时间会影响window 等键盘消失了再弹出
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            TimePickerView *picker = [TimePickerView showTimerPicker];
            picker.minimumDate = [NSDate stringToDate:@"1900-01-01"];
            picker.maximumDate = [NSDate date];
            picker.selectDate = [NSDate stringToDate:self.info.birthday];
            picker.datePickerMode = UIDatePickerModeDate;
            __weak typeof(TimePickerView) *weakPicker = picker;
            picker.sureBlock = ^(NSDate *selectDate){
                weakSelf.info.birthday = [selectDate convertDateToSting];
                [weakSelf.sourceTab reloadData];
                [weakPicker cancel];
            };
        });
    }
}

//拍照//相册
- (void)takeAvator
{
    UIActionSheet *action = [[UIActionSheet alloc]initWithTitle:@"选择图片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册选择",nil];
    [action showInView:self.view];
    [action handlerClickedButton:^(UIActionSheet *actionSheet, NSInteger btnIndex) {
        if (btnIndex == 0) {
            BOOL isCameraSupport = [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
            if (!isCameraSupport) {
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"相机不可用,请检查相机" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
            }else{
                UIImagePickerController *cameraPicker = [[UIImagePickerController alloc]init];
                cameraPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
                cameraPicker.allowsEditing = YES;
                [self presentViewController:cameraPicker animated:YES completion:nil];
                cameraPicker.delegate = self;
            }
        }else if (btnIndex == 1){
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
            imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            imagePicker.allowsEditing = YES;
            imagePicker.delegate = self;
            [self presentViewController:imagePicker animated:YES completion:nil];
        }
    }];
}
#pragma mark ---- UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    self.avatorImage = info[@"UIImagePickerControllerEditedImage"];
    [self.sourceTab reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
    //上传头像
    [self upLoadFile:self.avatorImage];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (UITableView *)sourceTab
{
    if (!_sourceTab) {
        _sourceTab = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH) style:UITableViewStylePlain];
        _sourceTab.dataSource = self;
        _sourceTab.delegate = self;
        _sourceTab.backgroundColor = RGBColorOne(240);
        _sourceTab.tableFooterView = [[UIView alloc]init];
        [_sourceTab registerNib:[UINib nibWithNibName:NSStringFromClass([PersonInfoViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([PersonInfoViewCell class])];
        [_sourceTab registerNib:[UINib nibWithNibName:NSStringFromClass([NickNamecell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([NickNamecell class])];
        [_sourceTab registerNib:[UINib nibWithNibName:NSStringFromClass([BirthDayTableViewCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([BirthDayTableViewCell class])];
    }
    return _sourceTab;
}
#pragma mark --------------------接口相关-------------------------
- (void)upLoadFile:(UIImage *)image
{
    [self showClearBgWaiter];
    [PersonNetWork upLoadImageWithParame:@{@"optionType":@"3"} image:image response:^(BOOL success, NSString *msg,NSString *path) {
        [self hideWaiter];
        self.info.portraitUrl = path;
    }];
}
- (void)saveInfo
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"token"] = [SZLAccountHelper shareInstance].token;
    parame[@"nickName"] = self.info.nickName;
    if (self.avatorImage) {
        parame[@"portraitUrl"] = self.info.portraitUrl;
    }
    parame[@"birthday"] = self.info.birthday;
    [self showWaiter];
    [PersonNetWork modifyPersonInfoWithParame:parame response:^(BOOL success, NSString *msg) {
        [self hideWaiter];
        if (success) {
            [MBProgressHUD showSuccess:@"资料修改成功" toView:self.view];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
            [[NSNotificationCenter defaultCenter]postNotificationName:ModifyUserInfoUpdate object:nil];
        }else{
            [MBProgressHUD showError:msg toView:self.view];
        }
    }];
}


@end
